// process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

import express from 'express';
import {metaRouter} from './metaRouter.js';
import {log} from "./utils/log.js";
import * as uuid from "uuid";
import log4js from "log4js";
import promMid from "express-prometheus-middleware";
import axios from "axios";
delete axios.defaults.headers.common['Accept'];
delete axios.defaults.headers.common['Content-Type'];
const app = express();
app.use(express.json());

// app.use(express.urlencoded({extended: true}));

app.use(promMid({
    metricsPath: '/metrics',
    collectDefaultMetrics: true,
    requestDurationBuckets: [0.1, 0.5, 1, 1.5],
    // requestLengthBuckets: [512, 1024, 5120, 10240, 51200, 102400],
    // responseLengthBuckets: [512, 1024, 5120, 10240, 51200, 102400],
    /**
     * Uncomenting the `authenticate` callback will make the `metricsPath` route
     * require authentication. This authentication callback can make a simple
     * basic auth test, or even query a remote server to validate access.
     * To access /metrics you could do:
     * curl -X GET user:password@localhost:9091/metrics
     */
    // authenticate: req => req.headers.authorization === 'Basic dXNlcjpwYXNzd29yZA==',
    /**
     * Uncommenting the `extraMasks` config will use the list of regexes to
     * reformat URL path names and replace the values found with a placeholder value
     */
    // extraMasks: [/..:..:..:..:..:../],
    /**
     * The prefix option will cause all metrics to have the given prefix.
     * E.g.: `app_prefix_http_requests_total`
     */
    // prefix: 'app_prefix_',
    /**
     * Can add custom labels with customLabels and transformLabels options
     */
    // customLabels: ['contentType'],
    // transformLabels(labels, req) {
    //   // eslint-disable-next-line no-param-reassign
    //   labels.contentType = req.headers['content-type'];
    // },
}));
app.use(async (req, res, next) => {
    try {
        let start = Date.now();
        let json = req.body;
        req.traceid = json.traceId ?? uuid.v4(); // 生成唯一标识符(traceid)
        req.traceid = req.traceid + ' ' + Date.now();
        req.log = log4js.getLogger('console');
        req.log.addContext('traceId', req.traceid)
        if (req.path === '/metasrv/query'){
            req.log.info(`${req.method} ${req.path} ${JSON.stringify(req.body)}`);
        }
        let r = await next(); // 调用下一个中间件函数
        // let duration = (Date.now() - start);
        // req.log.info(`${req.path}: ${duration}ms`);
    }catch(err) {
        log4js.getLogger('console').error(err.stack);
    }
});


app.use('/metasrv', metaRouter);

app.listen(8080);
log.warn('Server started on port 8080');